/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.db;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.sql.*;

import blueprint4j.utils.*;


public class FieldStringSequence extends FieldString {
    
    private static boolean table_exists = false;
    
    public FieldStringSequence( String p_name, int p_field_type ,String p_description,Entity entity ) {
        super( p_name,p_field_type,p_description,6,entity );
    }
    
    public Field newInstance(Entity entity) {
        return new FieldStringSequence(getName(),getFieldType(),getDescription(),entity);
    }
    
    public boolean isChanged() {
        if (getObject() == null || ((String)getObject()).length() == 0){
            return true;
        } else {
            return super.isChanged();
        }
    }
    
    
    private void createSeqTable()
    throws SQLException {
        if (!table_exists) {
            Statement smt = entity.getConnection().createStatement();
            try {
                smt.executeQuery(Entity.limitSQL(entity.getConnection(),"select * from d_seq_fields",1));
            } catch (SQLException sqle) {
                smt.execute("create table d_seq_fields(tablename varchar(200),sequence int)");
                table_exists = true;
            }
        }
    }
    
    public String getNextSequnce() {
        try {
            createSeqTable();
            String seq = null;
            Statement statement = entity.getConnection().createStatement();
            ResultSet rs = statement.executeQuery("select min(sequence) from d_seq_fields where tablename = '"+entity.getTableName()+"'");
            if (rs.next()) {
                seq = "000000".substring(0,6-(rs.getInt(1)+"").length()) + rs.getInt(1);
            }
            // if count is less than 5 create more
            rs = statement.executeQuery("select count(*) from d_seq_fields where tablename = '"+entity.getTableName()+"'");
            rs.next();
            int cnt = rs.getInt(1);
            if (cnt < 5) {
                // insert from max seq
                int start = 0;
                if (cnt > 0) {
                    rs = statement.executeQuery("select max(sequence) from d_seq_fields where tablename = '"+entity.getTableName()+"'");
                    rs.next();
                    start = rs.getInt(1);
                }
                for (int i = 0;i < 10;i++) {
                    DBTools.getLocalConnection(entity.getConnection()).execute("insert into d_seq_fields(tablename,sequence) values ('"+entity.getTableName()+"',"+(i+1+start)+")");
                }
            }
            if (seq == null) {
                return getNextSequnce();
            } else {
                deleteSequence(entity,Integer.parseInt(seq));
            }
            statement.close();
            return seq;
        } catch (Exception exception) {
            Log.critical.out(exception);
        }
        return null;
    }
    
    public void deleteSequence(Entity entity,int seq)
    throws SQLException,DataException {
        createSeqTable();
        DBTools.getLocalConnection(entity.getConnection()).execute("delete from d_seq_fields where tablename = '"+entity.getTableName()+"' and sequence = "+seq);
    }
    
    public void insertSequence()
    throws SQLException,DataException {
        createSeqTable();
        DBTools.getLocalConnection(entity.getConnection()).execute("insert into d_seq_fields(tablename,sequence) values ('"+entity.getTableName()+"',"+Integer.parseInt(get())+")");
    }
    
    public String get() {
        if (super.get() == null) {
            set(getNextSequnce());
        }
        return super.get();
    }
    
    public boolean isNull() {
        return false;
    }
}
